package net.huashitong.ssydt.provider.alipay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import net.huashitong.ssydt.provider.alipay.config.AlipayAppConfig;
import net.huashitong.ssydt.provider.alipay.entity.NotifyModel;
import net.huashitong.ssydt.provider.alipay.service.AlipaySuccessService;
import net.huashitong.ssydt.exceptions.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.08.17
 */
@Controller
@RequestMapping("/alipay/pay")
public class AlipayController {

    private AlipayAppConfig alipayAppConfig;

    private AlipaySuccessService alipaySuccessService;

    @Autowired
    public AlipayController(AlipayAppConfig alipayAppConfig, AlipaySuccessService alipaySuccessService) {
        this.alipayAppConfig = alipayAppConfig;
        this.alipaySuccessService = alipaySuccessService;
    }

    @RequestMapping("/notify")
    public void notifyUrl(HttpServletRequest request,
                          HttpServletResponse response,
                          @ModelAttribute NotifyModel model) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = AlipaySignature.rsaCheckV1(params, alipayAppConfig.getAlipayPublicKey(),
                alipayAppConfig.getInputCharset(),"RSA2");
        //验证成功
        if (flag){
            //支付成功
            if ("TRADE_SUCCESS".equals(model.getTrade_status())) {
                alipaySuccessService.paySuccess(model);
            }
            //验证成功
            writeText(response, "success");
        }else {
            //验证失败
            writeText(response, "fail");
        }
    }

    /**
     * 文本字符的输出
     * @param response
     * @param data
     */
    public void writeText(HttpServletResponse response, String data) {
        PrintWriter localPrintWriter = null;
        try {
            localPrintWriter = response.getWriter();
            localPrintWriter.print(data);
            localPrintWriter.flush();
        } catch (Exception e) {
            throw new ServiceException();
        } finally {
            if (localPrintWriter != null && !localPrintWriter.checkError()) {
                localPrintWriter.close();
            }
        }
    }


}
